/* 
 * 
 * Copyright (c) 2010 Photonic Games

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

using GameLevel;

namespace Game
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Level level;
        Matrix View, Projection;
        Model[] Models;

        public Game()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

#if true
            level = Content.Load<Level>("test");
            View = Matrix.CreateLookAt(
                new Vector3(0, 500, 1000), new Vector3(0, 0, 0), Vector3.Up);
#else
            level = Content.Load<Level>("test");
            View = Matrix.CreateLookAt(
                new Vector3(0, 3000, 6000), new Vector3(0, 0, 0), Vector3.Up);
#endif

            Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                    (float)GraphicsDevice.Viewport.AspectRatio, 1, 10000);

            

            //foreach (Model model in room.Geometry)
            for (int i = 0; i < level.Geometry.Length; i++)
            {
                Model model = level.Geometry[i];
                LevelModelParams param = (LevelModelParams)model.Tag;

                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (Effect effect in mesh.Effects)
                    {
                        effect.Parameters["World"].SetValue(Matrix.Identity);
                        effect.Parameters["View"].SetValue(View);
                        effect.Parameters["Projection"].SetValue(Projection);
                        
                        if (param.lightMapIndex >= 0)
                        {
                            effect.Parameters["LightmapTexture"].SetValue(level.Lightmaps[param.lightMapIndex]);
                        }
                    }
                }
            }

            //foreach (Model model in room.Geometry)
            for (int i = 0; i < level.GeometryModels.Length; i++)
            {
                

                foreach (Model model in level.GeometryModels[i].models)
                {
                    LevelModelParams param = (LevelModelParams)model.Tag;

                    foreach (ModelMesh mesh in model.Meshes)
                    {
                        foreach (Effect effect in mesh.Effects)
                        {
                            effect.Parameters["World"].SetValue(Matrix.Identity);
                            effect.Parameters["View"].SetValue(View);
                            effect.Parameters["Projection"].SetValue(Projection);

                            if (param.lightMapIndex >= 0)
                            {
                                effect.Parameters["LightmapTexture"].SetValue(level.Lightmaps[param.lightMapIndex]);
                            }
                        }
                    }
                }
            }

            Models = new Model[level.Models.Length];
            for (int i=0;i<level.Models.Length;i++)
            {
                Models[i] = Content.Load<Model>(level.Models[i].name);
            }

            
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 
        float mdlRotation = 0;

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            
            foreach (Model model in level.Geometry)
            {
                foreach (ModelMesh mesh in model.Meshes)
                {
                    mesh.Draw();
                }
            }


            for (int i = 0; i < level.Models.Length; i++)
            {
                Vector3 rotation = level.Models[i].rotation;

                rotation = rotation * MathHelper.Pi / 180f;

                // Correct for 90 degree rotation from WorldStudio
                Matrix worldMatrix = Matrix.CreateFromAxisAngle(Vector3.Up, -MathHelper.Pi / 2);
                worldMatrix *=
                    Matrix.CreateFromYawPitchRoll(rotation.Y, rotation.X, -rotation.Z);

                worldMatrix.Translation = level.Models[i].position;

                foreach (ModelMesh mesh in Models[i].Meshes)
                {
                    foreach (Effect effect in mesh.Effects)
                    {
                        effect.Parameters["World"].SetValue(worldMatrix);
                        effect.Parameters["View"].SetValue(View);
                        effect.Parameters["Projection"].SetValue(Projection);
                    }
                    mesh.Draw();
                }
            }

            for (int i = 0; i < level.GeometryModels.Length; i++)
            {
                mdlRotation += (float) gameTime.ElapsedGameTime.TotalSeconds* 10;

                Vector3 rotation = new Vector3(0,mdlRotation,0); //  level.GeometryModels[i].rotation;

                rotation = rotation * MathHelper.Pi / 180f;

                // Correct for 90 degree rotation from WorldStudio
                Matrix worldMatrix = Matrix.CreateFromAxisAngle(Vector3.Up, 0); // -MathHelper.Pi / 2);
                worldMatrix *=
                    Matrix.CreateFromYawPitchRoll(rotation.Y, rotation.X, -rotation.Z);

                worldMatrix.Translation = level.GeometryModels[i].position;
                foreach (Model model in level.GeometryModels[i].models)
                {
                    foreach (ModelMesh mesh in model.Meshes)
                    {
                        foreach (Effect effect in mesh.Effects)
                        {
                            effect.Parameters["World"].SetValue(worldMatrix);
                            effect.Parameters["View"].SetValue(View);
                            effect.Parameters["Projection"].SetValue(Projection);

                        }
                        mesh.Draw();
                    }
                }

                
            }

            foreach (Terrain terrain in level.Terrains)
            {

                Model model = terrain.model;

                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (Effect effect in mesh.Effects)
                    {

                        if (terrain.lightMap != null)
                        {
                            effect.Parameters["LightmapTexture"].SetValue(terrain.lightMap);
                        }

                        if (terrain.layers.Length > 1)
                        {
                            effect.Parameters["Alpha1Texture"].SetValue(terrain.layers[1].alpha);
                        }

                        effect.Parameters["World"].SetValue(Matrix.Identity);
                        effect.Parameters["View"].SetValue(View);
                        effect.Parameters["Projection"].SetValue(Projection);
                    }
                    mesh.Draw();
                }
            }

            base.Draw(gameTime);
        }
    }
}
